import MySQL
import Visualization


def skewness_accumulation_by_proportion():
    sql = 'SELECT * FROM hour_count'
    rows = MySQL.query(sql)
    c = {}
    maps = {'skewness': {'x': [], 'y': []}}
    date = 20160101
    while date <= 20160130:
        for hour in range(24):
            for row in rows:
                if row['date'] == str(date) and row['hour'] == hour:
                    if row['group'] not in c:
                        c[row['group']] = 0
                    c[row['group']] += row['count']
            sum_count = 0
            for k, v in c.items():
                sum_count += v
            avg = 1.0 / len(list(c.keys()))
            skewness = 0
            for k, v in c.items():
                skewness = skewness + (v / sum_count - avg) * (v / sum_count - avg) * (v / sum_count - avg)
            skewness = skewness / len(list(c.keys()))
            maps['skewness']['x'].append('%02d' % (date % 100) + '_' + '%02d' % hour)
            maps['skewness']['y'].append(skewness)
        date += 1
    Visualization.draw(maps, chart_type='line', x_label='time line', y_label='skewness value',
                       title='Skewness Variety in 30 days')
    return maps


def skewness_hour_by_proportion():
    sql = 'SELECT * FROM hour_count'
    rows = MySQL.query(sql)
    c = {}
    maps = {'skewness': {'x': [], 'y': []}}
    date = 20160101
    while date <= 20160130:
        for hour in range(24):
            for row in rows:
                if row['date'] == str(date) and row['hour'] == hour:
                    c[row['group']] = row['count']
            sum_count = 0
            for k, v in c.items():
                sum_count += v
            avg = 1.0 / len(list(c.keys()))
            skewness = 0
            for k, v in c.items():
                skewness = skewness + (v / sum_count - avg) * (v / sum_count - avg) * (v / sum_count - avg)
            skewness = skewness / len(list(c.keys()))
            maps['skewness']['x'].append('%02d' % (date % 100) + '_' + '%02d' % hour)
            maps['skewness']['y'].append(skewness)
        date += 1
    Visualization.draw(maps, chart_type='line', x_label='time line', y_label='skewness value',
                       title='Skewness Variety in 30 days')
    return maps


if __name__ == '__main__':
    MySQL.init('wiki')
    # skewness_accumulation_by_proportion()
    skewness_hour_by_proportion()

